package com.ly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.entity.Student;
import com.ly.entity.Team;
import com.ly.entity.User;
import com.ly.exception.ServiceException;
import com.ly.mapper.StudentMapper;
import com.ly.mapper.TeamMapper;
import com.ly.mapper.UserMapper;
import com.ly.pojo.dto.LoginDTO;
import com.ly.pojo.dto.RegisterDTO;
import com.ly.pojo.dto.UserDTO;
import com.ly.pojo.dto.updPwdDTO;
import com.ly.pojo.vo.UserVO;
import com.ly.service.UserService;
import com.ly.utils.Result;
import com.ly.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author : 黑渊白花
 * @ClassName UserServiceImpl
 * @date : 2025/2/8 16:39
 * @Description
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeamMapper teamMapper;
    private static final String DEFAULT_PASS = "123456";
    private static final String PASS_SALT = "encrypt";

    //
    @Override
    public UserVO login(LoginDTO loginDTO) {
        User user=null;
        try{
            QueryWrapper qw=new QueryWrapper();
            qw.eq("username",loginDTO.getUsername());
            user=userMapper.selectOne(qw);
        }catch (Exception e){
            log.error("根据用户名为{}查询出错", loginDTO.getUsername());
            throw new ServiceException("用户名错误");
        }
        if(user==null){
            throw new ServiceException("用户名或密码错误");
        }
        String password=user.getPassword();
        if(!password.equals(loginDTO.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        String token = TokenUtils.createToken(String.valueOf(user.getId()), user.getPassword());
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        userVO.setToken(token);
        //生成token
        return userVO;
    }

    @Override
    public void saveAndStudent(User user) {
        userMapper.insert(user);
        Student student=new Student();
        student.setUsername(user.getUsername());
        student.setUserId(user.getId());
        student.setName(user.getName());
        studentMapper.insert(student);
    }

    @Override
    public IPage<User> getPage(UserDTO userDTO) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(userDTO.getName()),User::getName,userDTO.getName());
        lqw.like(Strings.isNotEmpty(userDTO.getUsername()),User::getUsername,userDTO.getUsername());
        lqw.like(Strings.isNotEmpty(userDTO.getPhone()),User::getPhone,userDTO.getPhone());
        IPage page = new Page(userDTO.getPageNum(),userDTO.getPageSize());
        userMapper.selectPage(page,lqw);
        return page;
    }


    //修改用户表的时候首先先查学生表中是否存在这种用户
    @Override
    public void update(User user) {
        //先修改user表的username和name
        userMapper.updateById(user);
        QueryWrapper qw=new QueryWrapper();
        qw.eq("user_id",user.getId());
        Student student = studentMapper.selectOne(qw);
        student.setName(user.getName());
        student.setUsername(user.getUsername());
        studentMapper.updateById(student);

        QueryWrapper qw1=new QueryWrapper();
        qw1.eq("manager",user.getName());
        Team team = teamMapper.selectOne(qw1);
        if(team!=null){
            team.setManager(user.getName());
            teamMapper.updateById(team);
        }
    }


    @Override
    public User getByName(String name) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("name",name);
        User user = userMapper.selectOne(qw);
        if(user==null){
            return null;
        }
        //当前用户是社长，添加失败
        if(user.getType().equals("1")){
            return null;
        }
        //有这个用户并且如果他是学生把他设成社长
        if(user.getType().equals("2")){
            user.setType("1");
        }
        return user;
    }

    @Override
    public Boolean updPwd(updPwdDTO pwd) {
        User user = userMapper.selectById(pwd.getId());
        if(!user.getPassword().equals(pwd.getOldPwd())){
            return false;
        }
        user.setPassword(pwd.getNewPwd());
        userMapper.updateById(user);
        return true;
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
        User user = new User();

        BeanUtil.copyProperties(registerDTO,user);
        if(user==null){
            return Result.warn("用户消息不能为空");
        }
        //判断用户名称是否被注册
        QueryWrapper qw=new QueryWrapper();
        qw.eq("username",user.getUsername());
        User isExist = userMapper.selectOne(qw);
        if(isExist  !=  null){
            return Result.warn("用户账号存在");
        }
        userMapper.insert(user);
        Student student = new Student();
        BeanUtil.copyProperties(registerDTO,student);
        User user1 = userMapper.selectOne(qw);
        student.setUserId(user1.getId());
        studentMapper.insert(student);
        return Result.success("添加成功");
    }

    @Override
    public Result editInfo(RegisterDTO registerDTO) {
        User user = new User();
        BeanUtil.copyProperties(registerDTO,user);
        userMapper.updateById(user);
        QueryWrapper qw=new QueryWrapper();
        qw.eq("user_id",user.getId());
        Student student = studentMapper.selectOne(qw);

        student.setCollege(registerDTO.getCollege());
        student.setStuNumber(registerDTO.getStuNumber());
        student.setMajor(registerDTO.getMajor());
        studentMapper.updateById(student);

        QueryWrapper qw1=new QueryWrapper();
        qw1.eq("manager",user.getName());
        Team team = teamMapper.selectOne(qw1);
        if(team!=null){
            team.setManager(user.getName());
            teamMapper.updateById(team);
        }
        return Result.success();
    }


    private String securePass(String password){
        return SecureUtil.md5(password + PASS_SALT);
    }

}
